<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class Zhishidi_Bestsellers_Block_List extends Mage_Catalog_Block_Product_List {
    const SIDEBAR_CACHE_KEY = 'zhishidi_bestsellers_list';
    const XML_BEST_SELLERS_MODEL_PATH = 'zhishidi_bestsellers/settings';

    protected function _construct() {
        parent::_construct();
        $this->addData(array(
            'cache_lifetime' => 86400,
            'cache_tags' => array(self::SIDEBAR_CACHE_KEY),
        ));
    }
   

 
  protected  function _beforeToHtml() {
      $toolbar = $this->getToolbarBlock();
      $toolbar->setAvailableOrders(array('ordered_qty' => $this->__('Best Sellers')))
              ->setDefaultOrder('ordered_qty')
              ->setDefaultDirection('desc');
      return parent::_beforeToHtml();
  }
 
 
 
    protected function _getProductCollection() {
        if (is_null($this->_productCollection)) {
            //$attributes = Mage::getSingleton('catalog/config')->getProductAttributes();
            //$storeId = Mage::app()->getStore()->getId();
            $dataLimit = $this->getModel()->getLimitDate($this->getModel()->getPageDaysLimit());
            $collection = Mage::getResourceModel('reports/product_sold_collection')
                            //->addAttributeToSelect($attributes)
                            //->addOrderedQty()
                            //->addStoreFilter($storeId)
                            ->setDateRange($dataLimit['startdate'], $dataLimit['todaydate']) //
                            ->addAttributeToFilter('visibility', array('in' => array(Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG, Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)))
                            ->addAttributeToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
                            //->setOrder('ordered_qty', 'desc');

            $catId = $this->getModel()->getPageCategoriesID();
            if ($catId) {
                foreach ($catId as $id) {
                    $category = $this->getModel()->getCategory($id);
                    $collection->addCategoryFilter($category);
                }
            }

            $this->_productCollection = $collection;
        }

        return $this->_productCollection;
    }

    public function getLoadedProductCollection() {
        return $this->_getProductCollection();
    }

    protected function getModel() {
        return Mage::getModel(self::XML_BEST_SELLERS_MODEL_PATH);
    }

}

?>
